/*
 * MIT License
 *
 * Copyright (c) 2020 wen.gu <454727014@qq.com>
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in all
 * copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 */

/***************************************************************************
 * Name: xqueue.h
 *
 * Purpose: a queue base API define and implmentation
 *
 * Developer:
 *   wen.gu , 2023-08-03
 *
 * TODO:
 *
 ***************************************************************************/

#ifndef __XBUS_CORE_XQUEUE_H__
#define __XBUS_CORE_XQUEUE_H__

#include <cstdint>
#include <mutex>
#include <condition_variable>

#include "xbus/core/xresult.h"


namespace xbus::core {


template<typename T>
class XQueue {
protected:
    struct ValueNode {
        ValueNode* next = nullptr;
        T val;
        ValueNode(T v):val(v) {}
    };

public:
    XQueue(uint32_t max_limit = 0):max_size_limited_(max_limit){ } /** if set as 0, inidicate unlimited this size */
    virtual ~XQueue() {
        stop();
    }

public:
    XErrC push(T val) {
        if (!is_started_) { return XErrC::InvalidStatus; }        
        if ((max_size_limited_ > 0) && (size_ >= max_size_limited_)) { return XErrC::OutOfRange; }

        ValueNode* node = new ValueNode(val);

        std::lock_guard<std::mutex> l(lock_);
        if (list_tail_ == nullptr) {
            list_head_ = node;  //todo, is there maybe list_head_ not nullptr??
        } else {
            list_tail_->next = node;
        }    

        list_tail_ = node;
        size_++;
        return XErrC::OK;
    }
    /** timeout_ms: see also 'class WaitType',
     * NoWait: if the queue is emptry, then return immediately.
     * WaitForever: if the queue is emptry, then the pop() will be block until got new message or the queue is stopped.
     * > 0 : if the queue is emptry, then the pop() will be block until got new message or timeout or the queue is stopped.
    */
    XResult<T> pop(int32_t timeout_ms = WaitType::WaitForever) {
        if (!is_started_) { return XResult<T>::FromError(XErrC::InvalidStatus); }
        std::unique_lock<std::mutex> l(lock_);
        
        while ((list_head_ == nullptr)) {    
            if (timeout_ms == WaitType::NoWait) {
                return XResult<T>::FromError(XErrC::NotFound);
            } else if (timeout_ms == WaitType::WaitForever) {
                cv_.wait(l); 
            } else {
                if (cv_.wait_for(l, std::chrono::microseconds(timeout_ms)) == std::cv_status::timeout) { return XResult<T>::FromError(XErrC::TimeOut); }
            }
            
            if (!is_started_) { return XResult<T>::FromError(XErrC::InvalidStatus); }           
        }

        T val = list_head_->val;
        ValueNode* temp = list_head_;
        list_head_ = list_head_->next;
        delete temp;
        if (list_head_ == nullptr) {
            list_tail_ = nullptr;
        }
        size_--;
        return {val};
    }

    uint32_t size() const;
    void clear() {
        std::lock_guard<std::mutex> l(lock_);
        if (list_head_ == nullptr) {
            return ;
        }

        ValueNode* temp = nullptr;
        ValueNode* next = list_head_;
        while (next->next != list_head_) {
            temp = next;
            next = next->next;
            delete temp;
        }
        list_head_ = nullptr;
        size_ = 0;
    }
    bool empty() { return size_ == 0; }

    bool is_stopped() const { return !is_started_; }
public:
    XErrC start() {
        std::unique_lock<std::mutex> l(lock_);
        is_started_ = true;
        //cv_.notify_all();
        return XErrC::OK;
    }
    XErrC stop() {
        std::unique_lock<std::mutex> l(lock_);
        is_started_ = false;
        cv_.notify_all();
        return XErrC::OK;   
    }


protected:

    bool is_started_ = true;
    uint32_t size_ = 0; /** how many val in queue*/
    uint32_t max_size_limited_ = 0;
    ValueNode* list_head_ = nullptr;
    ValueNode* list_tail_ = nullptr;

    std::mutex lock_;
    std::condition_variable cv_;
};


} //namespace xbus::core


#endif /** !__XBUS_CORE_XQUEUE_H__ */